package com.shuoyue.ycgk.ui.course.playvideo;

import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.dueeeke.videocontroller.component.CompleteView;
import com.dueeeke.videocontroller.component.ErrorView;
import com.dueeeke.videocontroller.component.GestureView;
import com.dueeeke.videocontroller.component.PrepareView;
import com.dueeeke.videocontroller.component.TitleView;
import com.dueeeke.videoplayer.player.VideoView;
import com.dueeeke.videoplayer.util.L;
import com.shuoyue.ycgk.R;
import com.shuoyue.ycgk.appcatch.SPUtils;
import com.shuoyue.ycgk.base.BaseVideoActivity;
import com.shuoyue.ycgk.base.ListWithPage;
import com.shuoyue.ycgk.dkutils.ProgressManagerImpl;
import com.shuoyue.ycgk.entity.Course;
import com.shuoyue.ycgk.entity.CourseInfo;
import com.shuoyue.ycgk.entity.TimerTable;
import com.shuoyue.ycgk.entity.UserInfo;
import com.shuoyue.ycgk.ui.course.adapter.TimerTableSimpleAdapter;
import com.shuoyue.ycgk.ui.course.contract.CourseContract;
import com.shuoyue.ycgk.ui.pay.PreCourseOrderActivity;
import com.shuoyue.ycgk.utils.SizeUtil;
import com.shuoyue.ycgk.utils.UrlUtil;
import com.shuoyue.ycgk.views.dialog.common.HintConfirmDialog;
import com.shuoyue.ycgk.views.dialog.common.HintDialog;
import com.shuoyue.ycgk.views.dialog.speeddialog.SpeedDialog;
import com.shuoyue.ycgk.views.video.MyController;
import com.shuoyue.ycgk.views.video.MyVodControlView;

import java.util.ArrayList;
import java.util.List;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

public class PlayVideoActivity extends BaseVideoActivity<VideoView>
        implements CourseContract.CourseListView {

    @BindView(R.id.page_title)
    TextView pageTitle;
    @BindView(R.id.table)
    RecyclerView table;
    @BindView(R.id.player)
    VideoView player;
//    @BindView(R.id.speed)
//    Button speed;

    TitleView titleView;
    ImageView thumb;

    ArrayList<TimerTable> tables = new ArrayList<>();
    TimerTableSimpleAdapter mAdapter;
    int indexId = 0;
    CourseContract.Presenter presenter;
    //    String thumbUrl;
    MyController controller;
    MyVodControlView vodControlView;
//    LiveControlView liveControlView;

    CourseLearTimeContract.Presenter learTimePresenter;
    long learTime;//学习时间
    //    int courseId;
    Course course;

    //    final String SPExto = "play_viceo_time_catch";
    int isPay = 0;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_play_video;
    }

    @Override
    protected void initView() {
        pageTitle.setText("课程");
        initPlayer();
    }

    @Override
    public void initData() {
        presenter = new CourseContract.Presenter();
        learTimePresenter = new CourseLearTimeContract.Presenter();
        presenter.attachView(this);

        tables = (ArrayList<TimerTable>) getIntent().getSerializableExtra("table");
        indexId = getIntent().getIntExtra("play", 0);
        isPay = getIntent().getIntExtra("isPay", 0);

        course = (Course) getIntent().getSerializableExtra("course");
        setAllFalseSelect();
        findAllVideo(tables);
        for (TimerTable p : tables) {
            p.setSelect(openIndexPlaying(p));
        }
        mAdapter = new TimerTableSimpleAdapter(tables, isPay != 1, timerTable -> {
            reportNowPlayTime();
            setAllFalseSelect();
            presenter.getVideoInfo(timerTable);
        }, "章");
        table.setLayoutManager(new LinearLayoutManager(mContext));
        table.setAdapter(mAdapter);
        if (indexId != 0) {
            TimerTable t = findById(indexId);
            if (t != null) {
                presenter.getVideoInfo(t);
            }
        }
    }

    void setAllFalseSelect() {
        for (TimerTable timerTable : allVideos) {
            timerTable.setSelect(false);
        }
    }

    boolean openIndexPlaying(TimerTable ta) {
        if (ta.getId() == indexId) {
            ta.setPlaying(true);
            return true;
        } else if (ta.getNodes() != null) {
            for (TimerTable c : ta.getNodes()) {
                c.setSelect(openIndexPlaying(c));
                if (c.isSelect()) {
                    return true;
                }
            }
        }
        return false;
    }

    void initPlayer() {
//        liveControlView = new LiveControlView(this);//直播控制条
        vodControlView = new MyVodControlView(this);//点播控制条
        vodControlView.setSpeecDialogNotify(speecDialogNotify);
        mVideoView = findViewById(R.id.player);
        controller = new MyController(this);
        //根据屏幕方向自动进入/退出全屏
        controller.setEnableOrientation(true);
        PrepareView prepareView = new PrepareView(this);//准备播放界面
        thumb = prepareView.findViewById(R.id.thumb);//封面图
//        Glide.with(this).load(THUMB).into(thumb);
        controller.addControlComponent(prepareView);
        controller.addControlComponent(new CompleteView(this));//自动完成播放界面
        controller.addControlComponent(new ErrorView(this));//错误界面
        titleView = new TitleView(this);//标题栏
        controller.addControlComponent(titleView);
        //根据是否为直播设置不同的底部控制条
        controller.addControlComponent(vodControlView);
        GestureView gestureControlView = new GestureView(this);//滑动控制视图
        controller.addControlComponent(gestureControlView);
        //根据是否为直播决定是否需要滑动调节进度
        controller.setCanChangePosition(true);
        //设置标题
        String title = "测试";
        titleView.setTitle(title);
        //如果你不想要UI，不要设置控制器即可
        mVideoView.setVideoController(controller);
//            mVideoView.setDownloadUrl( "http://vfx.mtime.cn/Video/2019/03/14/mp4/190314223540373995.mp4");
        //保存播放进度
        mVideoView.setProgressManager(new ProgressManagerImpl());
        //播放状态监听
        mVideoView.addOnStateChangeListener(mOnStateChangeListener);
        setPhoneNum();

    }


    void play(String url, String title, String thumbImg, int trySee) {
        mVideoView.release();
        //设置标题
        titleView.setTitle(title);
        Glide.with(this).load(thumbImg).into(thumb);
//        HttpProxyCacheServer cacheServer = ProxyVideoCacheManager.getProxy(mContext);
//        String proxyUrl = cacheServer.getProxyUrl(downloadUrl);
        UrlUtil.UrlEntity urlEntity = UrlUtil.parse(url);

        mVideoView.setUrl(urlEntity.baseUrl, urlEntity.params);
        mVideoView.start();

        if (trySee != 0 && course.getIsFree() == 0) {
            controller.setProgressCallback((dur, pos) -> {
                if (pos > trySee * 1000) {
                    mVideoView.seekTo(0);
                    mVideoView.pause();
                    vodControlView.resetTimeTo0();
                    HintDialog hintDialog = new HintDialog(mContext, "提示", "试看已结束,请购买课程后观看");
                    hintDialog.show();
                }
            });
            setTrySeeTips(trySee);
//            handler.postDelayed(this::removeTrySee, 10000);
            setIsTrySee(true, trySee);
            controller.setCanChangePosition(false);
        } else {
            setIsTrySee(false, 0);
            controller.setProgressCallback(null);
            controller.setCanChangePosition(true);
            removeTrySee();
        }

    }

    void setIsTrySee(boolean canDrag, int trySeeTime) {
        if (vodControlView != null) {
            vodControlView.setIsTrySee(canDrag, trySeeTime);
        }
    }
//    void resetControllerBar(View view) {
//        ViewParent parent1 = liveControlView.getParent();
//        ViewParent parent2 = vodControlView.getParent();
//
//        if (parent1 != null) {
//            controller.removeView(liveControlView);
//        }
//        if (parent2 != null) {
//            controller.removeView(vodControlView);
//        }
//        controller.addView(view);
//    }

    /**
     * 统计学习时间,只统计正在播放的时间
     *
     * @param spaceTime
     */
    void addLearTime(long spaceTime) {
        if (mVideoView.getCurrentPlayState() == VideoView.STATE_PLAYING) {
            learTime = learTime + spaceTime;
        }
    }

    private VideoView.OnStateChangeListener mOnStateChangeListener = new VideoView.SimpleOnStateChangeListener() {
        @Override
        public void onPlayerStateChanged(int playerState) {
            switch (playerState) {
                case VideoView.PLAYER_NORMAL://小屏
                    break;
                case VideoView.PLAYER_FULL_SCREEN://全屏
                    break;
            }
        }

        @Override
        public void onPlayStateChanged(int playState) {
            switch (playState) {
                case VideoView.STATE_IDLE:
                    break;
                case VideoView.STATE_PREPARING:
                    //在STATE_PREPARING时设置setMute(true)可实现静音播放
//                    mVideoView.setMute(true);

                    break;
                case VideoView.STATE_PREPARED:
                    break;
                case VideoView.STATE_PLAYING:
                    //需在此时获取视频宽高
//                    String posSp = SPUtils.getPrefString(mContext, SPExto + indexId, "0");
//                    mVideoView.seekTo(Long.valueOf(posSp));
                    int[] videoSize = mVideoView.getVideoSize();
                    L.d("视频宽：" + videoSize[0]);
                    L.d("视频高：" + videoSize[1]);
                    handler.post(clock);
                    break;
                case VideoView.STATE_PAUSED:
                    handler.removeCallbacks(clock);
                    break;
                case VideoView.STATE_BUFFERING:
                    break;
                case VideoView.STATE_BUFFERED:
                    break;
                case VideoView.STATE_PLAYBACK_COMPLETED:
                    reportNowPlayTime();
                    findNext();
                    break;
                case VideoView.STATE_ERROR:
                    break;
            }
        }
    };

    SpeedDialog speedDialog;

    @OnClick({R.id.player, R.id.back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.player:
                break;
            case R.id.back:
                finish();
                break;
        }
    }

    @Override
    public void finish() {
        Intent intent = new Intent();
        intent.putExtra("table", tables);
        intent.putExtra("index", indexId);
        setResult(RESULT_OK, intent);
        super.finish();
    }

    @Override
    public void setCourseList(ListWithPage<Course> list) {

    }

    @Override
    public void setCourseInfo(CourseInfo info) {

    }

    @Override
    public void setVideoInfo(TimerTable timerTable, TimerTable adapterData) {
        indexId = timerTable.getId();
        play(timerTable.getUrl(), timerTable.getName(), TextUtils.isEmpty(course.getCover())
                ? "" : course.getCover(), timerTable.getTrySeeTime());
        adapterData.setSelect(true);
        mAdapter.notifyDataSetChanged();

    }

    @Override
    public void notBuyNotice() {
        HintConfirmDialog hintConfirmDialog = new HintConfirmDialog(mContext,
                "提示", "请先购买课程");
        hintConfirmDialog.setOkListener(v ->
                PreCourseOrderActivity.start(mContext, course, course.getDefaultPrice().getPrice()
                        , course.getDefaultPrice().getId(), course.getSubjectTypeId()));
        hintConfirmDialog.show();
    }


    TextView view;
    LinearLayout centerInfo;

    /*8
    设置试看提示
     */
    private void setTrySeeTips(int second) {
        centerInfo = (LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.lay_try_see_tips, null);
        TextView title = centerInfo.findViewById(R.id.title);
        TextView buy = centerInfo.findViewById(R.id.buy);
        buy.setOnClickListener(v -> PreCourseOrderActivity.start(mContext, course,
                course.getDefaultPrice().getPrice(),
                course.getDefaultPrice().getId(), course.getSubjectTypeId()));
        title.setText("试看" + (second >= 60 ? second / 60 + "分钟" : second + "秒") + ",观看完整课程请购买课程");
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(
                12,
                -1, -1,
                SizeUtil.dip2px(mContext, 16));
        centerInfo.setLayoutParams(layoutParams);
        layoutParams.gravity = Gravity.LEFT | Gravity.BOTTOM;
        ViewParent parent = centerInfo.getParent();
        if (parent != null) {
            controller.removeView(centerInfo);
        }
        controller.addView(centerInfo);
    }

    /**
     * 移除试看提示
     */
    private void removeTrySee() {
        if (centerInfo != null && centerInfo.getParent() != null) {
            controller.removeView(centerInfo);
        }
    }

    private void setPhoneNum() {
        UserInfo user = SPUtils.getUserInfo(mContext);
        if (controller == null || user == null) {
            return;
        }

        view = (TextView) LayoutInflater.from(mContext).inflate(R.layout.lay_simple_phone_num, null);
        view.setText(user.getPhone());
        ViewParent parent = view.getParent();
        if (parent != null) {
            controller.removeView(view);
        }
        controller.addView(view);
    }

    private void reset() {
        int height = controller.getHeight();
        int width = controller.getWidth();
        int childheight = view.getHeight();
        int childWidth = view.getWidth();
        int marginY = height - childheight;
        int marginX = width - childWidth;
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(getRandom(0, marginX), getRandom(0, marginY), -1, -1);
        view.setLayoutParams(layoutParams);
    }

//    private void updateVideoPosCatch() {
//        if (mVideoView.getCurrentPlayState() == VideoView.STATE_PLAYING)
//            SPUtils.setPrefString(mContext, SPExto + indexId, String.valueOf(mVideoView.getCurrentPosition()));
//    }

    public static int getRandom(int start, int end) {
        int num = (int) (Math.random() * (end - start + 1)) + start;
        return num;
    }

    Handler handler = new Handler();
    TimerTask clock = new TimerTask() {
        @Override
        public void run() {
            handler.postDelayed(clock, 2000);
            reset();
//            updateVideoPosCatch();
            addLearTime(2000);
        }
    };

//    @Override
//    protected void onResume() {
//        super.onResume();
//    }
//
//    @Override
//    protected void onPause() {
//        mVideoView.pause();
//        handler.removeCallbacks(clock);
//        super.onPause();
//    }

    @Override
    protected void onStop() {
        reportNowPlayTime();
        super.onStop();
    }

    @Override
    protected void onDestroy() {

        super.onDestroy();
    }

    HintDialog trySeeEndTip;
    MyVodControlView.ControllNotify speecDialogNotify = new MyVodControlView.ControllNotify() {
        @Override
        public void showSpeedDialog() {
            List<String> mDatas = new ArrayList<>();
            mDatas.add("0.75X");
            mDatas.add("1X");
            mDatas.add("1.25X");
            mDatas.add("1.5X");
            mDatas.add("2X");
            if (speedDialog == null) {
                speedDialog = new SpeedDialog(mContext, mDatas);
                speedDialog.addSelectCall(speed -> {
                    switch (speed) {
                        case "0.75X":
                            mVideoView.setSpeed(0.75f);
                            break;
                        case "1X":
                            mVideoView.setSpeed(1f);
                            break;
                        case "1.25X":
                            mVideoView.setSpeed(1.25f);
                            break;
                        case "1.5X":
                            mVideoView.setSpeed(1.5f);
                            break;
                        case "2X":
                            mVideoView.setSpeed(2f);
                            break;
                    }
                });
            }
            speedDialog.show();
        }

        @Override
        public void showBuyTips(long seekTo) {
            if (trySeeEndTip == null) {
                trySeeEndTip = new HintDialog(mContext, "提示", "试看已结束,请购买课程后观看");
            }
            if (!trySeeEndTip.isShowing()) {
                mVideoView.seekTo(0);
                mVideoView.pause();
                vodControlView.resetTimeTo0();
                trySeeEndTip.show();
            }
        }
    };
    List<TimerTable> allVideos = new ArrayList<>();

    void findAllVideo(List<TimerTable> tables) {
        for (TimerTable t : tables) {
            if (t.getIsLeaf() == 1) {
                allVideos.add(t);
            } else {
                findAllVideo(t.getNodes());
            }
        }
    }

    /**
     * 提交学习时间
     */
    void reportNowPlayTime() {
        learTimePresenter.setLearTime(course.getId(), (int) (learTime / 1000), indexId);
        learTime = 0;
    }

    void findNext() {
        for (int i = 0; i < allVideos.size(); i++) {
            TimerTable n = allVideos.get(i);
            if (n.getId() == indexId) {
                if (i < allVideos.size() - 1) {
                    indexId = allVideos.get(i + 1).getId();
                    for (TimerTable p : tables) {
                        p.setSelect(openIndexPlaying(p));
                    }
                    if (indexId != 0) {
                        TimerTable t = findById(indexId);
                        if (t != null) {
                            presenter.getVideoInfo(t);
                            return;
                        }
                    }
                }
            }
        }
    }

    TimerTable findById(int id) {
        for (TimerTable t : allVideos) {
            if (t.getId() == id) {
                return t;
            }
        }

        return null;
    }

}
